package com.charon.common.util;

import java.util.Date;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import net.sf.json.JSONObject;

public class JSUtils {
	public static JSONObject getKGSongListData(String songListId) {
		Document listDoc = ConnectionHandler
				.getResultDom("http://www.kugou.com/yy/special/single/" + songListId + ".html");
		String intro="";
		if(listDoc.getElementsByClass("more_intro")==null){
			 intro= listDoc.getElementsByClass("more_intro").get(0).text();
		};
		Elements elements = listDoc.select("script");
		Element element = elements.get(0).selectFirst("script");
		String eleData = element.toString();
		String createDate = listDoc.getElementsByClass("l").get(0).getElementsByClass("detail").get(0).textNodes()
				.get(6).toString();
		eleData = eleData.replace("<script type=\"text/javascript\">//歌曲数据", "");
		String data = eleData.replace("</script>", "");
		ScriptEngineManager manager = new ScriptEngineManager();
		ScriptEngine engine = manager.getEngineByName("javascript");
		try {
			engine.eval(data);
			engine.eval("function getSongList(){" + "var st = JSON.stringify(data);" + "return st;" + "}");
			engine.eval("function getSongListInfo(){" + "var st = JSON.stringify(specialData);" + "return st;" + "}");
			if (engine instanceof Invocable) {
				Invocable in = (Invocable) engine;
				JSONObject json = new JSONObject();
				json.put("songList", in.invokeFunction("getSongList").toString());
				json.put("songListInfo",in.invokeFunction("getSongListInfo").toString() );
				json.put("createDate",createDate);
				json.put("songListIntro", intro);
				return json;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}
